package com.luyuan.wxapp.controller;

import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSONObject;
import com.luyuan.common.core.domain.AjaxResult;
import com.luyuan.common.core.domain.entity.WxappUser;
import com.luyuan.common.core.domain.model.WxappLoginBody;
import com.luyuan.common.core.domain.model.WxappLoginUser;
import com.luyuan.common.core.domain.model.WxappPhoneBody;
import com.luyuan.common.core.domain.model.WxappUserResponse;
import com.luyuan.framework.web.service.WxappTokenService;
import com.luyuan.framework.web.service.WxappUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 微信小程序登录验证
 * 
 * @author luyuan
 */
@Api(value = "微信小程序登录和验证", tags = "wx_auth")
@RestController
@RequestMapping("/wxapp")
public class WxappController {
    private static final Logger log = LoggerFactory.getLogger(WxappController.class);

    @Autowired
    private WxappUserService wxappUserService;

    @Autowired
    private WxappTokenService wxappTokenService;

    /**
     * 微信小程序登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @ApiOperation(value = "微信小程序登录", notes = "登录接口", nickname = "wxlogin")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody WxappLoginBody loginBody) {
        try {   
            // 微信小程序登录
            WxappUserResponse userResponse = wxappUserService.login(loginBody.getCode(),
                    loginBody.getEncryptedData(), loginBody.getIv());
            if (userResponse.getToken() == null) {
                return AjaxResult.error("登录失败");
            }
            return AjaxResult.success(userResponse);
        } catch (Exception e) {
            log.error("微信登录失败", e);
            return AjaxResult.error("登录失败: " + e.getMessage());
        }
    }

    /**
     * 微信小程序用户信息更新
     * 
     * @param user    用户信息
     * @param request HTTP请求
     * @return 结果
     */
    @ApiOperation(value = "微信小程序用户信息更新", notes = "更新用户信息接口", nickname = "updateUserInfo")
    @PostMapping("/updateUserInfo")
    public AjaxResult updateUserInfo(@RequestBody WxappUser user, HttpServletRequest request) {
        try {
            // 获取登录用户信息
            WxappLoginUser loginUser = getLoginUser(request);
            if (loginUser == null) {
                return AjaxResult.error("用户未登录");
            }

            // 设置用户ID
            user.setUserId(loginUser.getUserId());

            // 调用服务层更新用户信息
            wxappUserService.updateWxappUser(user);

            // 更新缓存中的用户信息
            loginUser.setUser(user);
            wxappTokenService.setWxappLoginUser(loginUser);

            return AjaxResult.success("用户信息更新成功");
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return AjaxResult.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 验证token是否有效
     * 
     * @param request HTTP请求
     * @return 结果
     */
    @ApiOperation(value = "验证token是否有效", notes = "验证token接口", nickname = "checkToken")
    @GetMapping("/auth/checkToken")
    public AjaxResult checkToken(HttpServletRequest request) {
        try {
            WxappLoginUser loginUser = getLoginUser(request);
            if (loginUser != null) {
                return AjaxResult.success("token有效");
            } else {
                return AjaxResult.error("token无效或已过期");
            }
        } catch (Exception e) {
            return AjaxResult.error("token验证异常: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户信息
     * 
     * @param request HTTP请求
     * @return 结果
     */
    @ApiOperation(value = "获取当前登录用户信息", notes = "获取用户信息接口", nickname = "getUserInfo")
    @GetMapping("/auth/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) {
        try {
            WxappLoginUser loginUser = getLoginUser(request);
            if (loginUser != null) {
                return AjaxResult.success(loginUser.getUser());
            } else {
                return AjaxResult.error("用户未登录");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取用户信息异常: " + e.getMessage());
        }
    }

    /**
     * 获取微信用户手机号
     * 
     * @param phoneBody 手机号获取参数
     * @param request   HTTP请求
     * @return 手机号信息
     */
    @ApiOperation(value = "获取微信用户手机号", notes = "获取手机号接口", nickname = "getPhoneNumber")
    @PostMapping("/auth/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody WxappPhoneBody phoneBody, HttpServletRequest request) {
        try {
            // 验证用户是否登录
            WxappLoginUser loginUser = getLoginUser(request);
            if (loginUser == null) {
                return AjaxResult.error("用户未登录");
            }
            // 获取手机号信息
            JSONObject phoneInfo = wxappUserService.getPhoneNumber(
                    phoneBody.getCode(),
                    phoneBody.getEncryptedData(),
                    phoneBody.getIv());
            if (phoneInfo != null) {
                return AjaxResult.success(phoneInfo);
            } else {
                return AjaxResult.error("获取手机号失败");
            }
        } catch (Exception e) {
            log.error("获取微信手机号失败", e);
            return AjaxResult.error("获取手机号失败: " + e.getMessage());
        }
    }

    /**
     * 微信小程序退出登录
     * 
     * @param request HTTP请求
     * @return 结果
     */
    @ApiOperation(value = "微信小程序退出登录", notes = "退出登录接口", nickname = "wxlogout")
    @PostMapping("/logout")
    public AjaxResult logout(HttpServletRequest request) {
        try {
            String result = wxappUserService.logout(request);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("微信小程序退出登录异常", e);
            return AjaxResult.error("退出失败: " + e.getMessage());
        }
    }

    /**
     * 获取登录用户信息
     * 
     * @param request HTTP请求
     * @return 微信小程序登录用户
     */
    private WxappLoginUser getLoginUser(HttpServletRequest request) {
        return wxappTokenService.getWxappLoginUser(request);
    }
}